package com.effort.com.effort.excle.service;

import cn.hutool.core.util.IdUtil;
import com.effort.com.effort.excle.core.exception.ParamException;
import com.effort.com.effort.excle.core.util.ServerResponse;
import com.effort.com.effort.excle.core.util.validate.ValidateUtils;
import com.effort.com.effort.excle.param.ConnectionParam;
import com.effort.com.effort.excle.pool.InfluxDbPool;
import org.apache.commons.lang3.StringUtils;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ConnectionService {

    @Resource
    private InfluxDbPool influxDbPool;

    /**
     * 获取连接信息,然后加入到连接池之中去,返回连接对象给前端
     *
     * @param connectionParam
     * @return
     */
    public ServerResponse connect(ConnectionParam connectionParam) {
        InfluxDB connect = buildConnect(connectionParam);
        String key = IdUtil.fastSimpleUUID();
        influxDbPool.register(key,connect);
        return ServerResponse.builder().data(key).success(true).build();
    }

    /**
     * 清除连接信息
     * @return
     */
    public ServerResponse clearConnect() {
        this.influxDbPool.clear();
        return ServerResponse.ok("操作成功");
    }

    public ServerResponse resetConnect(ConnectionParam connectionParam) {
        InfluxDB connect = buildConnect(connectionParam);
        influxDbPool.register(connectionParam.getKey(),connect);
        return ServerResponse.builder().data(connectionParam.getKey()).success(true).build();
    }

    private InfluxDB buildConnect(ConnectionParam connectionParam) {
        ValidateUtils.validate(connectionParam);

        String url = "http://" + connectionParam.getIp() + ":" + connectionParam.getPort();

        InfluxDB connect = null;

        try {
            if (StringUtils.isEmpty(connectionParam.getUsername()) || StringUtils.isEmpty(connectionParam.getPassword())) {
                connect = InfluxDBFactory.connect(url);
            } else {
                connect = InfluxDBFactory.connect(url, connectionParam.getUsername(), connectionParam.getPassword());
            }
        } catch (Exception e) {
            throw new ParamException("连接信息出错,请检查连接信息");
        }
        return connect;
    }
}
